package com.cloudfun.campusshare.service.impl;

import com.cloudfun.campusshare.common.constant.Code;
import com.cloudfun.campusshare.common.exception.BusinessException;
import com.cloudfun.campusshare.common.model.vo.DeviceBrandAddVO;
import com.cloudfun.campusshare.common.model.vo.DeviceBrandDetailVO;
import com.cloudfun.campusshare.common.model.vo.DeviceBrandListVO;
import com.cloudfun.campusshare.common.response.PageResult;
import com.cloudfun.campusshare.common.security.AuthenticationHolder;
import com.cloudfun.campusshare.entity.DeviceBrandEntity;
import com.cloudfun.campusshare.repo.DeviceBrandEntityRepo;
import com.cloudfun.campusshare.repo.UserEntityRepo;
import com.cloudfun.campusshare.service.CreatorPersistenceService;
import com.cloudfun.campusshare.service.DeviceBrandService;
import com.cloudfun.campusshare.service.UserRelService;
import com.cloudfun.campusshare.util.BeanCopyUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : zhangyongjie
 * @version : 1.0
 * @createTime : 2020/5/8 16:05
 * @description :
 */
@Service
public class DeviceBrandServiceImpl extends CreatorPersistenceService implements DeviceBrandService {
    @Resource
    private DeviceBrandEntityRepo deviceBrandEntityRepo;

    @Autowired
    private UserRelService userRelService;

    @Resource
    private UserEntityRepo userEntityRepo;

    @Override
    protected Class<?> getEntityClass() {
        return DeviceBrandEntity.class;
    }

    @Override
    public void addDeviceBrand(DeviceBrandAddVO deviceBrandAddVO) {
        if (StringUtils.isBlank(deviceBrandAddVO.getId())) {
            DeviceBrandEntity entity = BeanCopyUtil.copy(deviceBrandAddVO, DeviceBrandEntity.class);
            deviceBrandEntityRepo.save(entity);
        } else {
            DeviceBrandEntity entity = deviceBrandEntityRepo.findById(deviceBrandAddVO.getId())
                    .orElseThrow(() -> new BusinessException(Code.ERROR, "没有id为:" + deviceBrandAddVO.getId() + "的设备品牌！"));
            entity.setName(deviceBrandAddVO.getName());
            entity.setChargeMan(deviceBrandAddVO.getChargeMan());
            entity.setChargeManPhone(deviceBrandAddVO.getChargeManPhone());
            entity.setServicePhone(deviceBrandAddVO.getServicePhone());
            deviceBrandEntityRepo.save(entity);
        }
    }

    @Override
    public PageResult queryDeviceBrandList(Pageable pageable, String keyword, String merchantId) {
        Page<DeviceBrandEntity> page = deviceBrandEntityRepo.findAll(assembleBrandSpecification(keyword, merchantId), pageable);
        return new PageResult(page.getTotalElements(), toDeviceBrandListVO(page.getContent()));
    }

    @Override
    public DeviceBrandDetailVO queryDeviceBrandDetail(String deviceBrandId) {
        DeviceBrandEntity entity = deviceBrandEntityRepo.findById(deviceBrandId).orElseThrow(() -> new BusinessException(Code.ERROR, "不存在id:" + deviceBrandId + "的设备品牌"));
        return BeanCopyUtil.copy(entity, DeviceBrandDetailVO.class);
    }

    @Override
    public void deleteDeviceBrand(String deviceBrandId) {
        if (AuthenticationHolder.isAdmin()) {
            deviceBrandEntityRepo.deleteById(deviceBrandId);
        } else {
            throw new BusinessException(Code.ERROR, "你无权删除id为:" + deviceBrandId + "的设备品牌");
        }
    }

    @Override
    public List<DeviceBrandListVO> getBrandList4DeviceEdit() {
        return toDeviceBrandListVO(deviceBrandEntityRepo.findAll(assembleBrandSpecification("", "")));
    }

    private List<DeviceBrandListVO> toDeviceBrandListVO(List<DeviceBrandEntity> list) {
        return list.stream().map(x -> {
            DeviceBrandListVO re = BeanCopyUtil.copy(x, DeviceBrandListVO.class);
            return re;
        }).collect(Collectors.toList());
    }

    private Specification<DeviceBrandEntity> assembleBrandSpecification(String keyword, String merchantId) {
        return ((root, query, criteriaBuilder) -> {
            List<Predicate> predicates = Lists.newArrayList();
            //不做数据权限控制
            if (StringUtils.isNotBlank(keyword)) {
                List<Predicate> likes = Lists.newArrayList();
                likes.add(criteriaBuilder.like(root.get("name"), keyword));
                likes.add(criteriaBuilder.like(root.get("chargeMan"), keyword));
                likes.add(criteriaBuilder.like(root.get("chargeManPhone"), keyword));
                likes.add(criteriaBuilder.like(root.get("servicePhone"), keyword));
                Predicate[] likeArr = new Predicate[likes.size()];
                predicates.add(criteriaBuilder.or(likes.toArray(likeArr)));
            }
            Predicate[] preArr = new Predicate[predicates.size()];
            return criteriaBuilder.and(predicates.toArray(preArr));
        });
    }

}
